#include "httpServer.hpp"
#include <memory>

using namespace server;
void USAGE(std::string proc)
{

    cout << "USAGE\r\n"
         << proc << "Usage error\r\n"
         << endl;
}

std::string suffixtoDes(std::string suffix)
{
    // 通过url的后缀给与不同的content-type
    string respheader = "Content-Type: ";
    if (suffix == ".html")
        respheader += "text/html";
    else if (suffix == ".jpg")
        respheader += "application/x-jpg";
    respheader += "\r\n";
    return respheader;
}
// 1. 服务器和网通分离，html
// 2. url-》 / ：
// 3. 需要正确的给客户端返回资源类型，首先需要自己知道！所有的资源都有后缀
bool Get(const Request &resq, Response &resp)
{
    // if(req.path == "test.py")
    // {
    //     //建立进程间通信，pipe
    //     //fork创建子进程，execl("/bin/python", test.py)
    //     // 父进程，将req.parm 通过管道写给某些后端语言，py，java，php等语言
    // }
    // if(req.path == "/search")
    // {
    //     // req.parm
    //     // 使用我们自己写的C++的方法，提供服务
    // }
    // for test
    cout << "-------------------------http start---------------------" << endl;
    cout << resq.inbuffer << endl;
    cout << "method: " << resq.method << endl;
    cout << "url: " << resq.url << endl;
    cout << "httpversion: " << resq.httpversion << endl;
    cout << "path: " << resq.path << endl;
    cout << "suffix: " << resq.suffix << endl;
    cout << "size: " << resq.size << endl;
    cout << "-------------------------http end---------------------" << endl;

    string respline = "HTTP/1.1  200 OK\r\n";
    string respheader = suffixtoDes(resq.suffix); //"Content-Type: text/html\r\n";,这里需要通过不同的后缀名选择不同的content-type的类型
    // 把长度也加上
    if (resq.size >= 0)
    {
        respheader += "Content-Length: ";
        respheader += std::to_string(resq.size);
        respheader += "\r\n";
    }

    string respblank = "\r\n";
    // std::string body = "<html lang=\"en\"><head><meta charset=\"UTF-8\"><title>for test</title><h1>hello world</h1></head><body><p>王应登，我宣你啊，baby</p></body></html>";
    // 通过读取的方式的方式来获取网页

    string body;
    // body.resize(resq.size+1);
    if (!Util::ReadFile(resq.path, &body)) // 如果读不到，就是资源不存在
    {
        const std::string html_404 = "./wwwroot/404.html";
        Util::ReadFile(html_404, &body);
    }

    resp.outbuffer += respline;
    resp.outbuffer += respheader;
    resp.outbuffer += respblank;
    resp.outbuffer += body;
    return true;
}

// ./httpServer 8080
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        USAGE(argv[0]);
        exit(0);
    }
    uint16_t port = atoi(argv[1]);
    unique_ptr<httpServer> httpsvr(new httpServer(Get, port));
    // httpsvr->registerCb("/", Get); // 功能路由！
    // httpsvr->registerCb("/search", Search);
    // httpsrv->registerCb("/test.py", Other);
    httpsvr->initServer();
    httpsvr->runServer();

    return 0;
}
